﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Pvf.Core.Converters
{
    internal sealed class PvfEnumConverter<TEnum> : PvfBinaryConverter<TEnum>
        where TEnum : struct
    {
        private readonly Dictionary<int, string> _valuesMapper = new Dictionary<int, string>();

        public override bool CanRead(BinaryReader reader)
        {
            var peek = reader.PeekChar();
            return peek == 2 || peek == 7;
        }

        protected override void OnInit()
        {
            PvfStatics.EnumMapSet(Layout.ObjType, Layout.Env, _valuesMapper);
        }

        public override TEnum Deserialize(BinaryReader reader, IPvfModule module = null)
        {
            var c = reader.PeekChar();

            TypeCheck(reader, 2, 7);

            var value = reader.ReadInt32();

            if (c == 2)
            {
                return Enum.TryParse(value.ToString(), out TEnum @enum) ? @enum : default;
            }
            else
            {
                if (_valuesMapper.TryGetValue(value, out var foundValue))
                {
                    return Enum.TryParse(foundValue, out TEnum @enum) ? @enum : default;
                }
                else
                {
                    Layout.Env.StringTable.TryGetValue(value, out var unhandledValue);

                    throw new KeyNotFoundException($"数值未找到:{unhandledValue}<{typeof(TEnum).FullName}>");
                }
            }
        }
    }
}
